import React, { useEffect, useState } from 'react';
import keycloak from '../config/keycloak';

const KeycloakTest = () => {
  const [keycloakInitialized, setKeycloakInitialized] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);
  const [username, setUsername] = useState('');
  const [error, setError] = useState(null);

  useEffect(() => {
    // 简单直接的初始化方式
    keycloak
      .init({
        onLoad: 'login-required',
        redirectUri: window.location.origin,
        checkLoginIframe: false
      })
      .then((auth) => {
        setKeycloakInitialized(true);
        setAuthenticated(auth);
        if (auth) {
          setUsername(keycloak.tokenParsed.preferred_username);
        }
      })
      .catch((err) => {
        setError(err.toString());
        console.error('Keycloak初始化失败:', err);
      });
  }, []);

  if (error) {
    return (
      <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
        <h2>Keycloak初始化错误</h2>
        <div style={{ color: 'red', marginBottom: '20px' }}>
          <pre>{error}</pre>
        </div>
        <h3>调试信息：</h3>
        <ul>
          <li>当前URL: {window.location.href}</li>
          <li>Origin: {window.location.origin}</li>
          <li>Keycloak URL: {keycloak.createLoginUrl()}</li>
        </ul>
        <button 
          onClick={() => window.location.reload()}
          style={{ padding: '10px 20px', marginTop: '20px' }}
        >
          重试
        </button>
      </div>
    );
  }

  if (!keycloakInitialized) {
    return <div>正在连接到认证服务器...</div>;
  }

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Keycloak测试页面</h2>
      
      {authenticated ? (
        <div>
          <p>认证状态: <span style={{ color: 'green' }}>已登录</span></p>
          <p>用户名: {username}</p>
          <button 
            onClick={() => keycloak.logout()}
            style={{ padding: '10px 20px', marginTop: '20px' }}
          >
            登出
          </button>
        </div>
      ) : (
        <div>
          <p>认证状态: <span style={{ color: 'red' }}>未登录</span></p>
          <button 
            onClick={() => keycloak.login()}
            style={{ padding: '10px 20px', marginTop: '20px' }}
          >
            登录
          </button>
        </div>
      )}
    </div>
  );
};

export default KeycloakTest;
